<?php

namespace app\command;

use app\api\model\Land;
use app\api\model\Massif;
use app\exceptions\ApiException;
use ba\Exception;
use EasyWeChat\Factory;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Order extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('Order');
        // 设置参数
        $this->setDescription('获取订单状态')->setHelp("php think Order");
    }

    protected function execute(Input $input, Output $output)
    {
        $app = Factory::miniProgram(config('wechat.xcx'));
        $order = (new \app\api\model\Order())->where(['status' => 2])->select()->toArray();
        if (!$order) {
            return;
        }
        foreach ($order as $item) {
            $data = $app->shipping->getOrder([
                'transaction_id' => $item['transaction_id'],
            ]);

            if ($data['errcode'] == 0 && $data['order']['order_state'] == 4) {
                try {
                    //更新订单
                    \think\facade\Db::startTrans();
                    (new \app\api\model\Order())->where(['id' => $item['id']])->update(['status' => 3, 'take_time' => time()]);
                    //更新地块状态
                    (new Massif())->where(['id' => $item['massif_id']])->update(['is_lock' => 0]);
                    //更新土地数量
                    (new Land())->where(['id' => $item['land_id']])->setInc('residue_nums');
                    \think\facade\Db::commit();
                } catch (Exception $e) {
                    \think\facade\Db::rollback();
                }
            }
        }
    }

}